package com.ds.infrastructure.audit.admin.service;

import com.ds.infrastructure.audit.admin.config.SSOConfig;
import com.ds.infrastructure.audit.admin.entry.UserInfo;
import com.ds.infrastructure.audit.admin.enums.Role;
import com.ds.infrastructure.audit.common.constant.CommonConstant;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * SSO接入文档： http://wiki.ds.com/pages/viewpage.action?pageId=30243577
 *
 * @date 2020/8/3
 */
@Slf4j
@Service
public class SSOService {

    private final RestTemplate restTemplate;

    private final SSOConfig ssoConfig;

    @Value("${system.administrators}")
    private List<String> administrators;

    @Autowired
    public SSOService(SSOConfig ssoConfig) {
        this.ssoConfig = ssoConfig;
        this.restTemplate = new RestTemplate();
    }

    @PostConstruct
    private void init() {
        log.info("Administrators={}", StringUtils.join(administrators, "|"));
    }

    /**
     * 校验ticket
     * http://sso.ds.com/api/rest/sso/serviceValidate?service=audit&ticket=123
     *
     * @param ticket
     * @return
     */
    public String validateTicket(String ticket) {
        log.info("====ValidateTicket={}", ticket);
        String url = ssoConfig.getValidateUrl() + "?service=" + ssoConfig.getService() + "&ticket=" + ticket;

        ResponseEntity<Sid> responseEntity;
        try {
            responseEntity = restTemplate.exchange(url, HttpMethod.GET, null, Sid.class);
        } catch (Exception e) {
            log.error("ValidateTicket exception: {} {}", url, e.getMessage());
            return null;
        }
        if (responseEntity.getStatusCode().isError()) {
            log.error("ValidateTicket error: {} {}", url, responseEntity.getStatusCodeValue());
            return null;
        }
        Sid sid = responseEntity.getBody();
        if (sid == null) {
            log.error("ValidateTicket got invalid response");
            return null;
        }
        return sid.getSid();
    }

    /**
     * 通过sid查询用户信息
     *
     * @param sid
     * @return
     */
    public UserInfo getUserInfo(String sid) {
        HttpHeaders headers = new HttpHeaders();
        headers.set(CommonConstant.HTTP_HEADER_AUTHORIZATION, sid);

        HttpEntity entity = new HttpEntity(headers);
        ResponseEntity<UserInfo> responseEntity;
        try {
            responseEntity = restTemplate.exchange(ssoConfig.getUserInfoUrl(), HttpMethod.GET, entity, UserInfo.class);
        } catch (RestClientException e) {
            log.error("GetUserInfo exception: {} {}", ssoConfig.getUserInfoUrl(), e.getMessage());
            return null;
        }
        if (responseEntity.getStatusCode().isError()) {
            log.error("GetUserInfo error: {} {}", ssoConfig.getUserInfoUrl(), responseEntity.getStatusCodeValue());
            return null;
        }
        UserInfo userInfo = responseEntity.getBody();
        if (userInfo != null) {
            userInfo.setSid(sid);
            if (administrators.contains(userInfo.getUsername())) {
                userInfo.setAuthority(Role.ROLE_ADMIN);
            } else {
                userInfo.setAuthority(Role.ROLE_USER);
            }
        }
        return userInfo;
    }

    @Data
    private static class Sid {
        private String sid;
        private String msg;
    }
}
